package io.github.cchenxi.crpc.core.cluster;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.util.CollectionUtils;

import io.github.cchenxi.crpc.core.api.Loadbalancer;

/**
 * 轮询负载均衡
 * Date: 2024-03-17
 *
 * @author chenxi
 */
public class RoundRibonLoadbalancer<T> implements Loadbalancer<T> {
    AtomicInteger index = new AtomicInteger(0);

    @Override
    public T choose(List<T> providers) {
        if (CollectionUtils.isEmpty(providers)) {
            return null;
        }
        if (providers.size() == 1) {
            return providers.get(0);
        }

        return providers.get((index.getAndIncrement() & Integer.MAX_VALUE) % providers.size());
    }
}
